package com.leectrl.adapter;


import android.content.SharedPreferences;
import android.os.Message;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hdl.school.application.MyApplication;
import com.hdl.school.bean.NetworkInfo;
import com.hdl.school.entity.NormalSerialCode;
import com.hdl.school.utils.SystemUtil;
import com.hdl.school.utils.TCWManager;
import com.hdl.school.utils.TimeUtil;
import com.hdl.school.utils.USBSerialManager;
import com.leectrl.bean.ZigbeeDevice;
import com.leectrl.utils.Bus;
import com.leectrl.utils.DbUtil;
import com.leectrl.utils.JsonUtil;
import com.leectrl.utils.StorageManager;
import com.likong.iotsdk.DeviceType;
import com.likong.iotsdk.RoomInfo;

import org.xutils.ex.DbException;
import org.xutils.x;

import java.net.InetSocketAddress;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;


public class UDPServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    //liuyong 判断两次进入分支的时间间距
    private long lastEnterTime = 0;
    SharedPreferences sharedPreferences=MyApplication.myApplication.getSharedPreferences("school_iot",0);
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg.copy().content();
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, CharsetUtil.UTF_8);
        System.out.println("【NOTE】>>>>>> 收到客户端的数据："+body);
        //liuyong
        //Log.e("UDP收到的数据：",body);
        if(body!=null&&body.length()>0&& JsonUtil.isJSON(body)){
            JSONObject revObj = JSON.parseObject(body);
            NetworkInfo networkInfo=TCWManager.getInstance(MyApplication.myApplication).getNetworkInfo();
            String action = revObj.getString("action");
            //liuyong 测试优化搜索设备卡
            if("tcp_serial".equals(action)){
                return;
            } else if ("searchTerminal".equals(action)) {
                JSONObject message = new JSONObject();
                String roomInfoStr=sharedPreferences.getString("room_info",null);
                String serverInfo=sharedPreferences.getString("serverConfig",null);
                message.put("action","deviceFound");
                message.put("device", "iot-terminal");
                message.put("from",msg.sender().getHostName());
                message.put("model",DeviceType.DEVICETYPE_CONTROLLER.toString());
                message.put("url","http://{$host}:8080");
                message.put("version",SystemUtil.getVersionName(MyApplication.myApplication));
                message.put("responseType","broadcast");
                message.put("ip",networkInfo.getIp());
                message.put("mac",networkInfo.getMac().toUpperCase());
                message.put("netmask",networkInfo.getNetmask());
                message.put("gateway",networkInfo.getGateway());
                message.put("dns",networkInfo.getDns());
                if(serverInfo!=null){
                    String[] sInfos=serverInfo.split(":");
                    message.put("server_ip",sInfos[0]);
                    message.put("server_port",sInfos[1]);
                }
                if(roomInfoStr!=null){
                    RoomInfo roomInfo=JSON.parseObject(roomInfoStr,RoomInfo.class);
                    message.put("room",roomInfo.getRoomId());
                    message.put("location",roomInfo.getRoomName());
                }
                ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                        JSON.toJSONString(message),CharsetUtil.UTF_8), new InetSocketAddress(
                        "255.255.255.255",msg.sender().getPort()))).sync();
            //liuyong 判断两次进入分支的时间要大于2秒
            } else if("searchAll".equals(action)){
                long currentTime = System.currentTimeMillis(); // 获取当前时间
                if (lastEnterTime == 0) { // 第一次进入
                    lastEnterTime = currentTime; // 记录当前时间
                } else { // 之后再次进入
                    long timeDiff = currentTime - lastEnterTime; // 计算与上次进入的时间差
                    if (timeDiff > 2000) { // 如果时间差大于5秒
                        // 进行需要的操作
                        JSONObject message = new JSONObject();
                        String roomInfoStr = sharedPreferences.getString("room_info", null);
                        String serverInfo = sharedPreferences.getString("serverConfig", null);
                        message.put("action", "deviceFound");
                        message.put("device", "iot-terminal");
                        message.put("from", msg.sender().getHostName());
                        message.put("model", DeviceType.DEVICETYPE_CONTROLLER.toString());
                        message.put("url", "http://{$host}:8080");
                        message.put("version", SystemUtil.getVersionName(MyApplication.myApplication));
                        message.put("responseType", "broadcast");
                        message.put("ip", networkInfo.getIp());
                        message.put("mac", networkInfo.getMac().toUpperCase());
                        message.put("netmask", networkInfo.getNetmask());
                        message.put("gateway", networkInfo.getGateway());
                        message.put("dns", networkInfo.getDns());
                        if (serverInfo != null) {
                            String[] sInfos = serverInfo.split(":");
                            message.put("server_ip", sInfos[0]);
                            message.put("server_port", sInfos[1]);
                        }
                        if (roomInfoStr != null) {
                            RoomInfo roomInfo = JSON.parseObject(roomInfoStr, RoomInfo.class);
                            message.put("room", roomInfo.getRoomId());
                            message.put("location", roomInfo.getRoomName());
                        }
                        ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                                JSON.toJSONString(message), CharsetUtil.UTF_8), new InetSocketAddress(
                                "255.255.255.255", msg.sender().getPort()))).sync();
                    }
                    lastEnterTime = currentTime; // 更新为当前时间，为下一次比较做准备
                }



            } else if ("updateNetwork".equals(action)) {
                if (networkInfo.getMac().toUpperCase().equals(revObj.getString("target"))) {
                    //修改网络配置
                    JSONObject config = revObj.getJSONObject("config");
                    JSONObject obj = new JSONObject();
                    obj.put("locip",config.getString("dev_ip"));
                    obj.put("locgetway",config.getString("dev_gateway"));
                    obj.put("locmask",config.getString("dev_netmask"));
                    obj.put("locdns",config.getString("dev_dns"));
                    Message message=new Message();
                    message.what=0;
                    message.obj=obj;
                    MyApplication.myApplication.handler.sendMessage(message);
                    sharedPreferences.edit().putString("serverConfig",config.getString("server_ip")+":"+config.getString("server_port")).commit();
                    if(config.containsKey("room")&&config.containsKey("location")){
                        RoomInfo roomInfo=new RoomInfo();
                        roomInfo.setRoomId(config.getIntValue("room"));
                        roomInfo.setRoomName(config.getString("location"));
                        sharedPreferences.edit().putString("room_info", JSON.toJSONString(roomInfo)).commit();
                    }

                    JSONObject respObj=new JSONObject();
                    respObj.put("action","updateNetworkSuccess");
                    ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                            JSON.toJSONString(respObj),CharsetUtil.UTF_8), new InetSocketAddress(
                            "255.255.255.255",msg.sender().getPort()))).sync();
                    Thread.sleep(1000);
                    TCWManager.getInstance(MyApplication.myApplication).reboot();
                }
            }else if ("bindComputer".equals(action)) {
                if (revObj.containsKey("controller")&&revObj.containsKey("computer")&&networkInfo.getMac().toUpperCase().equals(revObj.getJSONObject("controller").getString("mac"))){
                    String pcNo="1";
                    if(revObj.containsKey("pcNo")) {
                        pcNo = revObj.getString("pcNo");
                    }
                    if("1".equals(pcNo)){
                        sharedPreferences.edit().putString("computer_mac",revObj.getString("computer").replaceAll(":","")).commit();
                    }else{
                        sharedPreferences.edit().putString("computer_mac_"+pcNo,revObj.getString("computer").replaceAll(":","")).commit();
                    }
                    JSONObject respObj=new JSONObject();
                    respObj.put("action","bindControllerSuccess");
                    ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                            JSON.toJSONString(respObj),CharsetUtil.UTF_8), new InetSocketAddress(
                            "255.255.255.255",msg.sender().getPort()))).sync();
                }
            }else if("reboot".equals(action)){
                if (networkInfo.getMac().toUpperCase().equals(revObj.getString("target"))) {
                    JSONObject respObj=new JSONObject();
                    respObj.put("action","rebootSuccess");
                    ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                            JSON.toJSONString(respObj),CharsetUtil.UTF_8), new InetSocketAddress(
                            "255.255.255.255",msg.sender().getPort()))).sync();
                    Thread.sleep(1000);
                    TCWManager.getInstance(MyApplication.myApplication).reboot();
                }
            }else if("serial".equals(action)){
                //发送多条串口指令
                if (networkInfo.getMac().toUpperCase().equals(revObj.getString("target"))) {
                    JSONArray codes=revObj.getJSONArray("codes");
                    for(int i=0;i<codes.size();i++){
                        JSONObject codeItem=codes.getJSONObject(i);
                        if(codeItem.containsKey("delay")){
                            USBSerialManager.getInstence().sendCtrlSerialCode(codeItem.containsKey("portType")?codeItem.getString("portType"):null,codeItem.getString("code"),System.currentTimeMillis()+codeItem.getLongValue("delay"));
                        }else{
                            USBSerialManager.getInstence().sendCtrlSerialCode(codeItem.containsKey("portType")?codeItem.getString("portType"):null,codeItem.getString("code"),System.currentTimeMillis());
                        }
                    }
                    JSONObject respObj=new JSONObject();
                    respObj.put("action","serialSuccess");
                    respObj.put("target",revObj.getString("target"));
                    ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                            JSON.toJSONString(respObj),CharsetUtil.UTF_8), new InetSocketAddress(
                            "255.255.255.255",msg.sender().getPort()))).sync();
                }
            }else if("readConfig".equals(action)){
                if (networkInfo.getMac().toUpperCase().equals(revObj.getString("target"))) {
                    String key=revObj.getString("key");
                    if(key==null){
                        return ;
                    }
                    String value=sharedPreferences.getString("setting_"+key,null);
                    if(value==null){
                        return ;
                    }
                    sharedPreferences.edit().remove("setting_"+key).commit();
                    JSONObject respObj=new JSONObject();
                    respObj.put("action","readConfigSuccess");
                    respObj.put("key",key);
                    respObj.put("data",value);
                    respObj.put("target",revObj.getString("target"));
                    ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                            JSON.toJSONString(respObj),CharsetUtil.UTF_8), new InetSocketAddress(
                            "255.255.255.255",msg.sender().getPort()))).sync();
                }
            }else if("settingConfig".equals(action)){
                if (networkInfo.getMac().toUpperCase().equals(revObj.getString("target"))) {
                    String key=revObj.getString("key");
                    String value=revObj.getString("value");
                    if(key==null){
                        return ;
                    }
                    if(value==null){
                        String mValue=sharedPreferences.getString("c_setting_"+key,null);
                        if(mValue==null){
                            return ;
                        }
                        JSONObject respObj=new JSONObject();
                        respObj.put("action","settingConfig");
                        respObj.put("key",key);
                        respObj.put("type","read");
                        respObj.put("data",mValue);
                        respObj.put("target",revObj.getString("target"));
                        ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                                JSON.toJSONString(respObj),CharsetUtil.UTF_8), new InetSocketAddress(
                                "255.255.255.255",msg.sender().getPort()))).sync();
                    }else{
                        sharedPreferences.edit().putString("c_setting_"+key,value).commit();
                        JSONObject respObj=new JSONObject();
                        respObj.put("action","settingConfig");
                        respObj.put("type","write");
                        respObj.put("key",key);
                        respObj.put("target",revObj.getString("target"));
                        ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                                JSON.toJSONString(respObj),CharsetUtil.UTF_8), new InetSocketAddress(
                                "255.255.255.255",msg.sender().getPort()))).sync();
                    }
                }
            }else if("serialportConfig".equals(action)){
                if (networkInfo.getMac().toUpperCase().equals(revObj.getString("target"))) {
                    String type=revObj.getString("type");
                    JSONObject respObj=new JSONObject();
                    respObj.put("action","serialportConfig");
                    respObj.put("type",type);
                    if("read".equals(type)){
                        String serialportStr=sharedPreferences.getString("serialport",null);
                        if(serialportStr==null){
                            return ;
                        }
                        JSONObject serialObj=JSON.parseObject(serialportStr);
                        respObj.put("data",serialObj);
                    }else if("save".equals(type)){
                        sharedPreferences.edit().putString("serialport",revObj.getString("data")).commit();
                    }
                    respObj.put("target",revObj.getString("target"));
                    ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                            JSON.toJSONString(respObj),CharsetUtil.UTF_8), new InetSocketAddress(
                            "255.255.255.255",msg.sender().getPort()))).sync();
                }
            }else if("protocol".equals(action)){
                if (networkInfo.getMac().toUpperCase().equals(revObj.getString("target"))) {
                    String type=revObj.getString("type");
                    JSONObject respObj=new JSONObject();
                    respObj.put("action","protocol");
                    respObj.put("type",type);
                    if("read".equals(type)){
                        String protocolStr=sharedPreferences.getString("device_protocol",null);
                        if(protocolStr==null){
                            respObj.put("data","{}");
                        }else{
                            JSONObject protocolObj=JSON.parseObject(protocolStr);
                            respObj.put("data",protocolObj.getJSONObject("data").toJSONString());
                        }

                    }else if("save".equals(type)){
                        JSONObject protocolObj=new JSONObject();
                        protocolObj.put("data",JSONObject.parseObject(revObj.getString("data")));
                        sharedPreferences.edit().putString("device_protocol",protocolObj.toJSONString()).commit();
                    }
                    respObj.put("target",revObj.getString("target"));
                    ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                            JSON.toJSONString(respObj),CharsetUtil.UTF_8), new InetSocketAddress(
                            "255.255.255.255",msg.sender().getPort()))).sync();
                }
            }else if("resetPorts".equals(action)){
                if (networkInfo.getMac().toUpperCase().equals(revObj.getString("target"))) {
                    JSONObject respObj=new JSONObject();
                    respObj.put("action","resetPorts");
                    respObj.put("target",revObj.getString("target"));
                    ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                            JSON.toJSONString(respObj),CharsetUtil.UTF_8), new InetSocketAddress(
                            "255.255.255.255",msg.sender().getPort()))).sync();
                    sharedPreferences.edit().remove("serialport").commit();
                    Thread.sleep(1000);
                    TCWManager.getInstance(MyApplication.myApplication).reboot();
                }
            }else if("upgradeAPP".equals(action)){
                if (networkInfo.getMac().toUpperCase().equals(revObj.getString("target"))) {
                    String url=revObj.getString("url");
                    JSONObject respObj=new JSONObject();
                    respObj.put("action","upgradeAPP");
                    Message message=new Message();
                    message.what=6;
                    message.obj=url;
                    MyApplication.myApplication.handler.sendMessage(message);
                    respObj.put("target",revObj.getString("target"));
                    ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                            JSON.toJSONString(respObj),CharsetUtil.UTF_8), new InetSocketAddress(
                            "255.255.255.255",msg.sender().getPort()))).sync();
                }
            }else if("zigbee".equals(action)){
                if (networkInfo.getMac().toUpperCase().equals(revObj.getString("target"))) {
                    String type=revObj.getString("type");
                    JSONObject respObj=new JSONObject();
                    respObj.put("action","zigbee");
                    respObj.put("type",type);
                    if(type.equals("loadGatewayInfo")){
                        String gatewayIp=StorageManager.getInstance().getItem("gatewayIp");
                        String gatewayOnline=StorageManager.getInstance().getCacheItem("gatewayOnline");
                        respObj.put("gatewayIp",gatewayIp);
                        respObj.put("online",gatewayOnline.equals("1"));
                    }else if(type.equals("saveGatewayInfo")){
                        StorageManager.getInstance().setItem("gatewayIp",revObj.getString("ip"));
                    }else if(type.equals("deviceList")){
                        long count= DbUtil.getInstance().selector(ZigbeeDevice.class).count();
                        List<ZigbeeDevice> zigbeeDevices=DbUtil.getInstance().selector(ZigbeeDevice.class).findAll();
                        JSONArray jsonArray=new JSONArray();
                        if(zigbeeDevices!=null){
                            for(ZigbeeDevice zigbeeDevice:zigbeeDevices){
                                JSONObject jsonObject=new JSONObject();
                                jsonObject.put("tags",zigbeeDevice.getDeviceName());
                                String deviceType=zigbeeDevice.getDeviceType();
                                String typeStr=null;
                                if("zigbee-curtain".equals(deviceType)){
                                    typeStr="窗帘电机";
                                }else  if("airctrl-zigbee-leectrl".equals(deviceType)||"zigbee-airctrl".equals(deviceType)){
                                    typeStr="空调控制器";
                                }else if(deviceType.startsWith("zigbee-switcher")){
                                    typeStr="智能灯控面板";
                                }else if(deviceType.startsWith("zigbee-fan")){
                                    typeStr="智能风扇面板";
                                }else{
                                    typeStr=deviceType;
                                }
                                jsonObject.put("type_str",typeStr);
                                jsonObject.put("dev_key",zigbeeDevice.getDevicekey());
                                if(zigbeeDevice.getEnableTag()==null){
                                    String[] keys=zigbeeDevice.getDevicekey().split(",");
                                    StringBuffer stringBuffer=new StringBuffer();
                                    for(int i=0;i<keys.length;i++){
                                        stringBuffer.append("1,");
                                    }
                                    jsonObject.put("enable",stringBuffer.substring(0,stringBuffer.length()-1));
                                }else{
                                    jsonObject.put("enable",zigbeeDevice.getEnableTag());
                                }
                                jsonObject.put("mac",zigbeeDevice.getMac());
                                jsonObject.put("update_time", TimeUtil.date2String(zigbeeDevice.getCreateTime()));
                                jsonArray.add(jsonObject);
                            }
                        }
                        respObj.put("data",jsonArray);
                        respObj.put("count",count);
                    }else if(type.equals("delDevice")){
                        try {
                            ZigbeeDevice zigbeeDevice=DbUtil.getInstance().selector(ZigbeeDevice.class).where("mac","=",revObj.getString("mac")).findFirst();
                            DbUtil.getInstance().delete(zigbeeDevice);
                            Bus.getInstance().emit("zigbee_dev_event","update",zigbeeDevice);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }else if(type.equals("allowJoin")){
                        List<String> code = new ArrayList<>();
                        code.add("5c12");
                        code.add("07");
                        code.add("78");
                        code.add("w");
                        NormalSerialCode normalSerialCode = new NormalSerialCode();
                        normalSerialCode.setName("设备入网");
                        normalSerialCode.setCode(code);
                        Bus.getInstance().emit("zigbee_code", null, normalSerialCode);
                    }else if(type.equals("updateLines")){
                        try {
                            ZigbeeDevice zigbeeDevice=DbUtil.getInstance().selector(ZigbeeDevice.class).where("mac","=",revObj.getString("mac")).findFirst();
                            JSONArray lines=revObj.getJSONArray("lines");
                            StringBuffer keyBuffer=new StringBuffer();
                            StringBuffer nameBuffer=new StringBuffer();
                            StringBuffer enableBuffer=new StringBuffer();
                            for(int i=0;i<lines.size();i++){
                                JSONObject line=lines.getJSONObject(i);
                                nameBuffer.append(line.getString("tag"));
                                keyBuffer.append(line.getString("key"));
                                enableBuffer.append(line.getBoolean("enableTag")?"1":"0");
                                nameBuffer.append(",");
                                keyBuffer.append(",");
                                enableBuffer.append(",");
                            }
                            zigbeeDevice.setDeviceName(nameBuffer.substring(0,nameBuffer.length()-1));
                            zigbeeDevice.setDevicekey(keyBuffer.substring(0,keyBuffer.length()-1));
                            zigbeeDevice.setEnableTag(enableBuffer.substring(0,enableBuffer.length()-1));
                            DbUtil.getInstance().update(zigbeeDevice);
                            Bus.getInstance().emit("zigbee_dev_event","update",zigbeeDevice);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }else if(type.equals("saveDevice")){
                        JSONArray checkedLine=revObj.getJSONArray("checkedLine");
                        ZigbeeDevice zigbeeDevice=new ZigbeeDevice();
                        zigbeeDevice.setMac(revObj.getString("mac"));
                        zigbeeDevice.setDeviceType(revObj.getString("dev_type"));
                        StringBuffer keyBuffer=new StringBuffer();
                        StringBuffer nameBuffer=new StringBuffer();
                        StringBuffer enableBuffer=new StringBuffer();
                        for(int i=0;i<checkedLine.size();i++){
                            JSONObject line=checkedLine.getJSONObject(i);
                            nameBuffer.append(line.getString("title"));
                            keyBuffer.append(line.getString("line"));
                            enableBuffer.append(line.getBoolean("enable")?"1":"0");
                            nameBuffer.append(",");
                            keyBuffer.append(",");
                            enableBuffer.append(",");
                        }
                        zigbeeDevice.setDeviceName(nameBuffer.substring(0,nameBuffer.length()-1));
                        zigbeeDevice.setDevicekey(keyBuffer.substring(0,keyBuffer.length()-1));
                        zigbeeDevice.setEnableTag(enableBuffer.substring(0,enableBuffer.length()-1));
                        zigbeeDevice.setCreateTime(new Date(System.currentTimeMillis()));
                        try {
                            DbUtil.getInstance().saveOrUpdate(zigbeeDevice);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }

                        Bus.getInstance().emit("zigbee_dev_event","add",zigbeeDevice);
                    }
                    respObj.put("target",revObj.getString("target"));
                    ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                            JSON.toJSONString(respObj),CharsetUtil.UTF_8), new InetSocketAddress(
                            "255.255.255.255",msg.sender().getPort()))).sync();
                }
            }else if("roomTree".equals(action)){
                if (!networkInfo.getMac().toUpperCase().equals(revObj.getString("target"))) {
                    return ;
                }
                org.xutils.http.RequestParams params = new org.xutils.http.RequestParams();
                SharedPreferences sharedPreferences = MyApplication.myApplication.getSharedPreferences("school_iot", 0);
                String serverConfigStr = sharedPreferences.getString("serverConfig", null);
                if (serverConfigStr == null) {
                    return ;
                }
                params.setUri("http://" + serverConfigStr + "/publicapi/terminal/room/tree/load");
                try {
                    String result = x.http().getSync(params, String.class);
                    JSONObject respObj=new JSONObject();
                    respObj.put("action","roomTree");
                    respObj.put("data",JSON.parseArray(result));
                    respObj.put("target",revObj.getString("target"));
                    ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                            JSON.toJSONString(respObj),CharsetUtil.UTF_8), new InetSocketAddress(
                            "255.255.255.255",msg.sender().getPort()))).sync();
                } catch (Throwable throwable) {
                    throwable.printStackTrace();
                }
            }else if("roomBind".equals(action)){
                if (!networkInfo.getMac().toUpperCase().equals(revObj.getString("target"))) {
                    return ;
                }
                JSONObject respObj=new JSONObject();
                respObj.put("action","roomBind");
                SharedPreferences sharedPreferences = MyApplication.myApplication.getSharedPreferences("school_iot", 0);
               if(revObj.containsKey("value")){
                   respObj.put("type","save");
                   RoomInfo roomInfo=new RoomInfo();
                   roomInfo.setRoomName(revObj.getString("name"));
                   roomInfo.setRoomId(revObj.getIntValue("value"));
                   sharedPreferences.edit().putString("room_info",JSON.toJSONString(roomInfo)).commit();
                   String serverConfig = sharedPreferences.getString("serverConfig", null);
                   org.xutils.http.RequestParams params = new org.xutils.http.RequestParams();
                   params.setUri("http://" + serverConfig + "/publicapi/terminal/network/info/upload");
                   params.addParameter("mac", networkInfo.getMac());
                   params.addParameter("room_id", roomInfo.getRoomId());
                   params.addParameter("dev_id", DeviceType.DEVICETYPE_CONTROLLER.toString());
                   try {
                       x.http().getSync(params, String.class);
                   } catch (Throwable throwable) {
                       throwable.printStackTrace();
                   }
               }else{
                   respObj.put("type","read");
                   String roomInfoStr = sharedPreferences.getString("room_info", null);
                   if(roomInfoStr!=null){
                       RoomInfo roomInfo=JSON.parseObject(roomInfoStr,RoomInfo.class);
                       respObj.put("data",roomInfo.getRoomId());
                   }
               }
                respObj.put("target",revObj.getString("target"));
                ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                        JSON.toJSONString(respObj),CharsetUtil.UTF_8), new InetSocketAddress(
                        "255.255.255.255",msg.sender().getPort()))).sync();

            }else if("testServer".equals(action)){
                if (!networkInfo.getMac().toUpperCase().equals(revObj.getString("target"))) {
                    return ;
                }
                org.xutils.http.RequestParams params = new org.xutils.http.RequestParams();
                SharedPreferences sharedPreferences = MyApplication.myApplication.getSharedPreferences("school_iot", 0);
                String serverConfigStr = sharedPreferences.getString("serverConfig", null);
                if (serverConfigStr == null) {
                    return ;
                }
                params.setUri("http://" + serverConfigStr + "/publicapi/terminal/sys/getTime");
                JSONObject respObj=new JSONObject();
                respObj.put("action","testServer");
                try {
                    x.http().getSync(params, String.class);
                    respObj.put("result",true);
                } catch (Throwable throwable) {
                    throwable.printStackTrace();
                    respObj.put("result",false);
                }
                respObj.put("target",revObj.getString("target"));
                ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                        JSON.toJSONString(respObj),CharsetUtil.UTF_8), new InetSocketAddress(
                        "255.255.255.255",msg.sender().getPort()))).sync();
            }

        }
    }
}
